/*
 * Copyright (c) 2011 Imre Fazekas.
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 * Neither the name of the Brillien nor the names of its
 * terms and concepts may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package com.vii.streamline.services.db;

import com.vii.streamline.services.MathServices;
import com.vii.streamline.services.db.transaction.BrillienTransaction;
import com.vii.streamline.services.db.transaction.FXID;
import com.vii.streamline.services.error.StreamLineException;

import javax.transaction.Transaction;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * Simple implementation of interface {@link DBMediator}
 */
public class SimpleDBMediator implements DBMediator {

    protected static String                     global_id;

    /** The vendor of the database. */
    protected String                            vendor;

    /** The user name of the database. */
    protected String                            username;

    /** The password of the database. */
    protected String                            password;

    /** The address of the database. */
    protected String                            address;

    /** The port of the database. */
    protected String                            port;

    /** The database name. */
    protected String                            database;

    /** Indicates if the database is XA capable or not. */
    protected boolean                           xaCapable;

    /** The {@link javax.sql.DataSource} of the database.. */
    protected javax.sql.DataSource              ds;

    protected ConcurrentLinkedQueue<Connection> connections;

    /**
     * User for Transactions
     */
    protected String                            id;

    static{
        global_id = MathServices.randomId( 8 );
    }

    {
        address     = "localhost";
        username    = "";
        password    = "";

        connections = new ConcurrentLinkedQueue<Connection>();

        id = MathServices.randomId( 8 );
    }

    public static SimpleDBMediator newSimpleDBMediator(String vendor, String username, String password, String database, boolean xaCapable){
        Map<String, String> vendorInfo = DBServices.DB_VENDORS.get( vendor );
        return new SimpleDBMediator(
            vendor, username, password, "localhost", vendorInfo.get("defaultPort"), database, xaCapable
        );
    }
    public static SimpleDBMediator newSimpleDBMediator(String vendor, String username, String password, String database){
        return newSimpleDBMediator( vendor, username, password, database, false );
    }

    /**
     * Instantiates a new {@link DBMediator}.
     */
    public SimpleDBMediator() {
    }

    /**
     * Instantiates a new dB mediator.
     * @param vendor The vendor of the database.
     * @param username The user name of the database.
     * @param password The password of the database.
     * @param address The address of the database.
     * @param port The port of the database.
     * @param database The name of the database.
     */
    public SimpleDBMediator(String vendor, String username, String password, String address, String port, String database) {
        this.vendor = vendor;
        this.username = username;
        this.password = password;
        this.address = address;
        this.port = port;
        this.database = database;
    }

    /**
     * Instantiates a new dB mediator.
      @param vendor The vendor of the database.
     * @param username The user name of the database.
     * @param password The password of the database.
     * @param address The address of the database.
     * @param port The port of the database.
     * @param database The name of the database.
     * @param xaCapable Indicates if the database is xa capable or not.
     */
    public SimpleDBMediator(String vendor, String username, String password, String address, String port, String database, boolean xaCapable) {
        this.vendor = vendor;
        this.username = username;
        this.password = password;
        this.address = address;
        this.port = port;
        this.database = database;
        this.xaCapable = xaCapable;
    }

    /**
     * Gets the vendor.
     */
    @Override
    public String getVendor() {
        return vendor;
    }

    /**
     * Sets the vendor.
     */
    @Override
    public void setVendor(String vendor) {
        this.vendor = vendor;
    }

    /**
     * Gets the user name.
     */
    @Override
    public String getUsername() {
        return username;
    }

    /**
     * Sets the user name.
     */
    @Override
    public void setUsername(String username) {
        this.username = username;
    }

    /**
     * Gets the password.
     */
    @Override
    public String getPassword() {
        return password;
    }

    /**
     * Sets the password.
     */
    @Override
    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * Gets the address.
     */
    @Override
    public String getAddress() {
        return address;
    }

    /**
     * Sets the address.
     */
    @Override
    public void setAddress(String address) {
        this.address = address;
    }

    /**
     * Gets the port.
     */
    @Override
    public String getPort() {
        return port;
    }

    /**
     * Sets the port.
     */
    @Override
    public void setPort(String port) {
        this.port = port;
    }

    /**
     * Gets the name of the database.
     */
    @Override
    public String getDatabase() {
        return database;
    }

    /**
     * Sets the name of the database.
     */
    @Override
    public void setDatabase(String database) {
        this.database = database;
    }

    /**
     * Checks whether or not the database is xa capable.
     */
    @Override
    public boolean isXaCapable() {
        return xaCapable;
    }

    /**
     * Sets the xa capable.
     */
    @Override
    public void setXaCapable(boolean xaCapable) {
        this.xaCapable = xaCapable;
    }

    /**
     * Gets the {@link javax.sql.DataSource}.
     */
    @Override
    public javax.sql.DataSource getDs() {
        return ds;
    }

    /**
     * Sets the {@link javax.sql.DataSource}.
     */
    @Override
    public void setDs(javax.sql.DataSource ds) {
        this.ds = ds;
    }

    @Override
    public <T extends Transaction> T startTransaction() throws StreamLineException {
        FXID fxId = FXID.fill( global_id, this.id );
        BrillienTransaction transaction = new BrillienTransaction( fxId );
        return (T)transaction;
    }

    @Override
    public <T extends Transaction> void closeTransaction( T t ) throws StreamLineException {
        try {
            t.commit();
        } catch ( Exception e) {
            throw new StreamLineException( e );
        }
    }


    /**
     * Requests a new Connection
     */
    public Connection getConnection( boolean autocommit, int isolation ) throws StreamLineException {
        try {
            Connection c = getConnection();
            c.setAutoCommit( autocommit );
            c.setTransactionIsolation( isolation );
            return c;
        } catch (SQLException e) {
            throw new StreamLineException( e );
        }
    }

    /**
     * Requests a new Connection
     */
    public Connection getConnection( boolean autocommit ) throws StreamLineException {
        return getConnection( autocommit, Connection.TRANSACTION_READ_COMMITTED );
    }

    /**
     * Requests a new Connection
     */
    public Connection getConnection() throws StreamLineException {
        try {
            if( ds == null )
                throw new StreamLineException( "DataSource instance is null!" );

            Connection c = ds.getConnection();
            connections.add( c );
            return c;
        } catch (SQLException e) {
            throw new StreamLineException( e );
        }
    }

    /**
     * Retrieves a previously requests connection
     */
    public void retrieveConnection( Connection c ) throws StreamLineException {
        try {
            c.close();
            connections.remove( c );
        } catch (SQLException e) {
            throw new StreamLineException( e );
        }
    }

    public void retrieveConnections() throws StreamLineException {
        for (Connection connection : connections) {
            try {
                connection.close();
            } catch (SQLException e) { e.printStackTrace(); }
        }
        connections.clear();
    }

    @Override
    public String toString() {
        return "DBMediator{" +
                "vendor='" + vendor + '\'' +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", address='" + address + '\'' +
                ", port='" + port + '\'' +
                ", database='" + database + '\'' +
                ", xaCapable=" + xaCapable +
                '}';
    }
}
